import {getRequest} from "./api";


export const initMenu = (router, store)=> {
    //如果vuex里面有菜单信息,通行
    if(store.state.routes.length>0){
        return;
    }
    getRequest("/system/config/menu").then(data=>{
        if(data){
            let fmtRoutes = formatRoutes(data);
            router.addRoutes(fmtRoutes);
            store.commit('initRoutes',fmtRoutes);
        }
    })
}

export  const formatRoutes=(routes)=>{
    let fmRoutes = [];
    routes.forEach(router=>{
        //此处定义多个变量赋值给router
        let{
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        //如果children不为空且是一个数组而不是null
        if(children && children instanceof Array){
            children=formatRoutes(children);//递归调用
        }
        let fmRouter = {
            path:path,
            name:name,
            iconCls:iconCls,
            meta:meta,
            children:children,
            component(resolve) {
                //动态导入
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmRoutes.push(fmRouter);
    })
    return fmRoutes;
}
